package org.example.sdpback.controller;

import com.alibaba.excel.EasyExcel;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.example.sdpback.domain.entity.TestCase;
import org.example.sdpback.domain.po.TestCaseFilePO;
import org.example.sdpback.domain.vo.TestCaseFileVO;
import org.example.sdpback.domain.vo.TestCaseVO;
import org.example.sdpback.sdk.listenners.TestCaseDataListener;
import org.example.sdpback.sdk.response.SdpResponseData;
import org.example.sdpback.service.TestCaseService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ProjectName: sdp-back
 * @Package: org.example.sdpback.controller
 * @ClassName: FileProcessController
 * @Author: zhuxingyue
 * @Description: 文件处理
 * @Date: 2025/8/1 13:56
 * @Version: 1.0
 **/
@RestController
@RequestMapping("/fileProcess")
@Tag(name = "文件处理")
@RequiredArgsConstructor
public class FileProcessController {

    private final TestCaseService testCaseService;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public SdpResponseData<String> uploadFile(@RequestPart("file") MultipartFile file) throws IOException {
        // 处理文件逻辑
        try {
            // 获取上传文件的输入流
            InputStream inputStream = file.getInputStream();

            // 读取Excel文件
            EasyExcel.read(inputStream)
                    .head(TestCaseFilePO.class)
//                    .registerConverter(new TestCaseLevelEnumConverter())
                    .registerReadListener(new TestCaseDataListener(testCaseService))
                    .sheet()
                    .doRead();

        } catch (IOException e) {
            throw new IOException("文件上传失败");
        }

        return SdpResponseData.success("文件上传成功");
    }


    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        // 设置响应头（强制下载，UTF-8处理中文名）
        String fileName = URLEncoder.encode("用户数据", "UTF-8").replaceAll("\\+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 写入数据流（自动关闭流）
        List<TestCaseVO> testCaseList = testCaseService.getTestCaseList();

        // 数据转换
        List<TestCaseFileVO> dataList = testCaseList.stream().map(testCase -> {
            TestCaseFileVO testCaseFileVO = new TestCaseFileVO();
            testCaseFileVO.setName(testCase.getName());
            testCaseFileVO.setLevel(testCase.getLevel());
            testCaseFileVO.setType(testCase.getType());
            testCaseFileVO.setApiPath(testCase.getApiPath());
            return testCaseFileVO;
        }).collect(Collectors.toList());

        EasyExcel.write(response.getOutputStream(), TestCaseFileVO.class).sheet("Sheet").doWrite(dataList);
    }

}
